neutron.setTitle("Permission")
neutron.setMinSize(540, 300)
neutron.getInfo((data) => {
    if (data[0]["h"] < 300) {
        neutron.setWinSize(540, 300)
    }
});

var username = ""
var permission_var_table = {
    0: "[0] 禁止",
    1: "[1] 只读",
    2: "[2] 读写"
}
var permissioninfo = {}
function load_permission_list() { // 获取权限列表
    var xhr = new XMLHttpRequest()
    xhr.open("GET", API_PATH + "/user/permission?" + new URLSearchParams({ "username": username }), true)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
                return
            }
            var permission = data["data"]
            document.getElementById("permissions").innerHTML = ""
            for (var i = 0; i < permission.length; i++) { // 权限列表
                (function (i) {
                    var template = `<div class="permission" id="permission-id-${i}">
                    <span class="permission_path"></span>
                    <button class="permission_value inline_btn" type="button" onclick="change_permission(${i})"></button>
                    <button class="permission_remove inline_btn" type="button" onclick="rm_permission(${i})">x</button>
                    <div class="permission_dbid" style="display:none;">${permission[i][2]}</div>
                </div>`
                    document.getElementById("permissions").innerHTML += template
                    setTimeout(() => {
                        document.getElementById("permission-id-" + i).getElementsByClassName("permission_path")[0].innerText = permission[i][0]
                        document.getElementById("permission-id-" + i).getElementsByClassName("permission_value")[0].innerText = permission_var_table[permission[i][1]]
                    }, 0)
                }(i));
            }
        }
    }
    xhr.send()
}
function contains(list, value) { // 判断列表中是否包含某个值
    for (var i = 0; i < list.length; ++i) {
        if (list[i] === value) return true;
    }
    return false;
}
function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}
window.onload = function () {
    username = new URLSearchParams(location.search).get("username")
    document.getElementById("username").innerText = username
    neutron.setTitle("Permission - " + username)
    load_permission_list()

    // 获取权限注解
    var xhr = new XMLHttpRequest()
    xhr.open("GET", API_PATH + "/user/permissioninfo", true)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
                return
            }
            permissioninfo = data["data"]
        }
    }
    xhr.send();

    // 拖拽
    var main_obj = document.getElementById("permissions");
    (['dragenter', 'dragover', 'dragleave', 'drop']).forEach(eventName => {
        main_obj.addEventListener(eventName, preventDefaults, false);
    });
    main_obj.addEventListener('drop', (e) => {
        if (!contains(e.dataTransfer.types, "application/neutron-file-transfer")) {
            return
        }
        var datas = JSON.parse(e.dataTransfer.getData("application/neutron-file-transfer"))
        // 处理 from
        var pathbase = datas["from"]
        if (pathbase == "/") {
            pathbase = ""
        }
        var all_len = datas.filelist.length
        var success_len = 0
        // 遍历多个文件
        for (var i = 0; i < datas.filelist.length; i++) {
            (function (i) { // 环境隔离
                var xhr = new XMLHttpRequest()
                xhr.open("POST", API_PATH + "/user/permission?" + new URLSearchParams({
                    "username": username,
                    "path": pathbase + "/" + datas.filelist[i]["name"],
                    "permission": 0
                }))
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var data = JSON.parse(xhr.responseText)
                        success_len++
                        if (data["code"] != 0) {
                            alert(data["msg"])
                        }
                        if (success_len == all_len) {
                            load_permission_list() // 刷新权限
                        }
                    }
                }
                xhr.send()
            })(i);
        }
    })
}
function change_permission(id) { // 修改权限
    var permission_elem = document.getElementById('permission-id-' + id).getElementsByClassName("permission_value")[0]
    var rect = permission_elem.getBoundingClientRect()
    neutron.showContextMenu((ret) => { // 下拉菜单
        var data_permission = ret[0]
        document.getElementById('permission-id-' + id).getElementsByClassName("permission_value")[0].innerText = permission_var_table[ret[0]]
        var xhr = new XMLHttpRequest()
        xhr.open("POST", API_PATH + "/user/permission?" + new URLSearchParams({
            "username": username,
            "path": document.getElementById('permission-id-' + id).getElementsByClassName("permission_path")[0].innerText,
            "permission": data_permission
        }), true) // 这里发送的是 path
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = JSON.parse(xhr.responseText)
                if (data["code"] != 0) {
                    alert(data["msg"])
                } else {
                    load_permission_list() // 刷新权限
                }
            }
        }
        xhr.send();
    }, ["[0] 禁止", "[1] 只读", "[2] 读写"], rect.left, rect.top + 28)
}

function rm_permission(id) {
    var permission_elem = document.getElementById('permission-id-' + id).getElementsByClassName("permission_remove")[0]
    var rect = permission_elem.getBoundingClientRect()
    neutron.showContextMenu((ret) => {
        if (ret[0] != 0) {
            return
        }
        var xhr = new XMLHttpRequest()
        xhr.open("POST", API_PATH + "/user/permission/remove?" + new URLSearchParams({
            "dbid": parseInt(document.getElementById('permission-id-' + id).getElementsByClassName("permission_dbid")[0].innerText),
            "username": username,
        })) // 这里发送的是 id
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = JSON.parse(xhr.responseText)
                if (data["code"] != 0) {
                    alert(data["msg"])
                } else {
                    load_permission_list()
                }
            }
        }
        document.getElementById('permission-id-' + id).outerHTML = ""
        xhr.send();
    }, ["确定"], rect.left, rect.top - 4)
}

function add_permission_path() {
    var btn_elem = document.getElementById('path_btn')
    var rect = btn_elem.getBoundingClientRect()
    neutron.showContextMenu((ret) => {
        if (ret[0] == 0) {
            neutron.createIframeWin("Open", "/api/plugin/filemanager/iframe/index.html?" + (new URLSearchParams({
                "choose": "file",
                "choose_callback": neutron.winid,
                "choose_callback_id": "open"
            }).toString()
            ), 0, 0)
        }
        else if (ret[0] == 1) {
            neutron.createIframeWin("Open", "/api/plugin/filemanager/iframe/index.html?" + (new URLSearchParams({
                "choose": "dir",
                "choose_callback": neutron.winid,
                "choose_callback_id": "open"
            }).toString()
            ), 0, 0)
        }
        else if (ret[0] == 2) {
            var path = prompt("请输入路径")
            add_permission_callback(path)
        }
    }, ["文件", "文件夹", "输入"], rect.left, rect.top + 24)
}

function add_permission_callback(path) {
    if (path == null || path == "") {
        return
    }
    var xhr = new XMLHttpRequest()
    xhr.open("POST", API_PATH + "/user/permission?" + new URLSearchParams({
        "username": username,
        "path": path,
        "permission": 0
    }), true)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                load_permission_list()
            }
        }
    }
    xhr.send();
}

function add_permission_plugin() {
    var rect = document.getElementById("add_permission_plugin_btn").getBoundingClientRect()
    var plug_info_lst = Object.keys(permissioninfo)
    neutron.showContextMenu((ret) => {
        if (ret[0] == 0) {
            var xhr = new XMLHttpRequest()
            xhr.open("POST", API_PATH + "/user/permission?" + new URLSearchParams({
                "username": username,
                "path": "//plugin",
                "permission": 0
            }), true)
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = JSON.parse(xhr.responseText)
                    if (data["code"] != 0) {
                        alert(data["msg"])
                    } else {
                        load_permission_list()
                    }
                }
            }
            xhr.send();
        }
        var data = ret[0] - 1
        var values = permissioninfo[plug_info_lst[data]]
        neutron.showContextMenu((ret) => {
            var data2 = ret[0] // 生成路径
            if (data2 == 0) {
                var path = "//plugin/" + plug_info_lst[data]
            } else {
                var path = "//plugin/" + plug_info_lst[data] + "/" + Object.keys(values)[data2 - 1]
            }
            var xhr = new XMLHttpRequest()
            xhr.open("POST", API_PATH + "/user/permission?" + new URLSearchParams({
                "username": username,
                "path": path,
                "permission": 0
            }), true)
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = JSON.parse(xhr.responseText)
                    if (data["code"] != 0) {
                        alert(data["msg"])
                    } else {
                        load_permission_list()
                    }
                }
            }
            xhr.send();
        }, ["插件", ...Object.values(values)], rect.left, rect.top + 24) // 注解列表
    }, ["所有插件", ...plug_info_lst], rect.left, rect.top + 24) // 注解列表
}

window.addEventListener("message", winapi_receiveMessage, false); // 接收选择文件回调
function winapi_receiveMessage(event) {
    if (event.origin != location.origin) {
        return;
    }
    var data = event.data;
    if (data["id"] == "open") {
        console.log(data["data"])
        add_permission_callback(data["data"])
    }
}

